﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;

namespace HelpCentral.Configuration
{
    public static class CoreContainer
    {
        static readonly IDictionary<Type, Type> types = new Dictionary<Type, Type>();

        public static void Register<TContract, TImplementation>()
        {
            types[typeof(TContract)] = typeof(TImplementation);
        }

        public static TContract ResolveNew<TContract>()
        {
            return (TContract)ResolveNew(typeof(TContract));
        }

        public static object ResolveNew(Type contract)
        {
            Type implementation = types[contract];

            ConstructorInfo constructor = implementation.GetConstructors()[0];

            ParameterInfo[] constructorParameters = constructor.GetParameters();

            if (constructorParameters.Length == 0)
                return Activator.CreateInstance(implementation);

            List<object> parameters = new List<object>(constructorParameters.Length);

            foreach (ParameterInfo parameterInfo in constructorParameters)
                parameters.Add(ResolveNew(parameterInfo.ParameterType));

            return constructor.Invoke(parameters.ToArray());
        }
    }

}
